<template>
  <div class="system-customer">
    <xr-header/>

    <div class="customer-content">
      <div class="system-view-nav">
        <Tree :data="categoryData" expand="true" default-expand-all="true" @on-select-change="refreshTask"></Tree>

      </div>

      <div class="system-view-content" >
        <div class="option-bar">
          <el-row type="flex" justify="start">
            <el-form :inline="true" :model="queryForm" class="demo-form-inline" label-width='80px' inline  size='mini'
                     style="margin-left: -15px;">
              <el-form-item label="流程名称">
                <el-input v-model="queryForm.procDefName" clearable></el-input>
              </el-form-item>
              <el-form-item label="实例标题">
                <el-input v-model="queryForm.subject"  clearable></el-input>
              </el-form-item>


              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
                <el-button type="default" @click="reset">重置</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </div>
        <el-row class="margin:30px;">
          <el-col>
            <el-table
              :data="tableData"
              size="mini"
              style="width: 100%"
              :height="tableHeight"
            >
              <el-table-column
                label="序号"
                fixed
                type="index"
                width="50"
                fixed
                align="center">
                <template slot-scope="scope">
                  <span>{{(queryForm.page-1 ) * queryForm.pageSize + scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="startUserNo"
                label="发起人"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column

                prop="procDefName"
                label="流程名称"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                fixed
                prop="subject"
                label="实例标题"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="title"
                label="流程标题"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="接收时间"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="endTime"
                label="结束时间"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="duration"
                label="持续时间"
                show-overflow-tooltip

              >


              </el-table-column>
              <el-table-column
                prop="statusDesc"
                label="状态"
              >
                <template slot-scope="scope">



                  <el-tag v-if="scope.row.status=='completed'" type="info">结束</el-tag>
                  <el-tag v-else-if="scope.row.status=='running'" type="success">流转</el-tag>
                  <el-tag v-else-if="scope.row.status=='invalid'" type="danger">作废</el-tag>
                  <el-tag v-else-if="scope.row.status=='end'" type="warning">结束</el-tag>
                  <el-tag v-else type="error">-</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="100"


              >
                <template slot-scope="scope">
                  <el-button   size='mini' type='text'   @click="handleClick(scope.row)">激活</el-button>


                </template>
              </el-table-column>

            </el-table>
          </el-col>
        </el-row>
        <div class="p-contianer">
          <el-pagination
            background
            class="p-bar"
            @current-change="handleCurrentChange"
            :current-page="queryForm.page"
            :page-size="queryForm.pageSize"
            layout="prev, pager, next, sizes, total, jumper"
            :total="total">
          </el-pagination>
        </div>



      </div>
    </div>



  </div>


</template>
<style rel="stylesheet/scss" lang="scss" scoped>
  .p-contianer {
    position: relative;
    background-color: white;
    height: 44px;
    .p-bar {
      float: right;
      margin: 5px 100px 0 0;
      font-size: 14px !important;
    }
  }
  .option-bar {
    padding: 15px 20px;
  }
  .system-customer {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    padding: 0 15px;
  }
  .customer-content {
    flex: 1;
    position: relative;
    display: flex;
    overflow: hidden;
  }
  .system-view-nav {
    min-width: 200px;
    background: #fff;
    margin-right: 10px;
    padding-top: 20px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;

  }
  .system-view-content {
    flex: 1;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    background: #fff;
    display: flex;
    flex-direction: column;
    overflow-x: auto;
  }

  // 菜单
  .menu-item {
    color: #333;
    font-size: 13px;
    padding: 0 15px;
    height: 40px;
    line-height: 40px;
    cursor: pointer;
    position: relative;
    .icon-close {
      position: absolute;
      top: 0;
      right: 8px;
      z-index: 1;
      display: none;
    }
  }

  .menu-item:hover,
  .menu-item.is-select {
    background-color:  #F6F8FA;
  }

  .menu-item:hover::before,
  .menu-item.is-select::before {
    content: ' ';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 2px;
    background-color: #5383ed;
  }
</style>

<script>
  import {getTaskData, getTaskChartData, getBpmnModelCategory, getModelerJson, publishModel, getVar,uploadSaveModel,exportModelById,ipLog} from "@/api/analy";
  import Footer from '../../../common/footer';
  import {codemirror} from 'vue-codemirror'
  import "codemirror/theme/ambiance.css";  // 这里引入的是主题样式，根据设置的theme的主题引入，一定要引入！！
  require("codemirror/mode/javascript/javascript"); // 这里引入的模式的js，根据设置的mode引入，一定要引入！！
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import {getHisInstanceList} from "@/api/analy";
  import XrHeader from '@/components/XrHeader'

  export default {
    name: 'Task',
    components: {
      Footer, codemirror,Treeselect,XrHeader
    },

    data() {
      var checkKey = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('别名不能为空'));
        }
        var PLACEHOLDER_REGEX = /\$\{([^}]*)\}/g;
        var SPACE_REGEX = /\s/;
        value=value.replace(PLACEHOLDER_REGEX, '$1');
        if (SPACE_REGEX.test(value)) {
          return callback(new Error('Key不能包含空格'));

        }
        var ID_REGEX = /^[a-z_][\w-.]*$/i;
        var QNAME_REGEX = /^([a-z][\w-.]*:)?[a-z_][\w-.]*$/i;

        if (!ID_REGEX.test(value)) {
          if (QNAME_REGEX.test(value)) {
            return callback(new Error('别名不能包含前缀.'));
          }
          return callback(new Error('别名必须是一个有效的QName'));
        }
        return  callback();
      };
      return {

        uploadFormRuleValidate: {
          name: [
            {required: true, message: '    ', trigger: 'blur'}
          ],
          groupName: [
            {required: true, message: '    ', trigger: 'blur'}
          ],
          modelKey: [
            {required: true, message: '    ', trigger: 'blur'},
            { validator: checkKey, trigger: 'blur' }
          ]
        },
        baseUploadURL: process.env.VUE_APP_BASE_BPM_API+"/a1bpmn/api/upload/model",
        uploadForm: {
          name: "",
          modelKey: '',
          id: "",
          description: '',
          typeId: null,
          groupName: null,
        },
        tableData: [],
        tableHeight: 450,
        queryDate: [],
        total: 0,
        chartVisible: false,
        code: false,
        varHtml: "",
        modelerModal: false,
        uploadModal: false,
        viewImageModeler: false,
        chartData: {},
        baseURL: process.env.VUE_APP_BASE_BPM_API,
        modelerSrc: process.env.VUE_APP_BASE_BPM_API + "diagram/index.html",
        viewImageModelerSrc: process.env.VUE_APP_BASE_BPM_API + "view/def.html?&modelId=",
        viewImageModelerTmpSrc: "",
        shopName: [],
        statusList: [
          {label: "未发布", value: "0"},
          {label: "已发布", value: "1"},
        ],
        queryForm: {
          name: "",
          procDefName: "",
          subject: "",
          createTime: "",
          endTime: "",
          tmpCreateTime: "",
          tmpEndTime: "",
          page: 1,
          limit: 10,
          pageSize: 10,

          whereSql: "",
          typeKey: ""
        },
        categoryData: [],
        uploadList: [],
      }
    },
    mount() {
      this.getData()
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop
    },
    created() {
      this.getData()
    },
    methods: {
      recursionWindow:function(){
      },
      handleResetForm:function(){
        this.uploadForm.name="";
        this.uploadForm.modelKey="";
        this.uploadForm.id="";
        this.uploadForm.description="";
        this.uploadForm.typeId=null;
        this.uploadForm.groupName=null;
      },
      save: function () {
        this.$refs['uploadForm'].validate((valid) => {
          if (valid) {
            var formData = this.uploadForm;
            if (this.uploadList.length==0){
              this.$message({"duration":800,message:'模型文件必须上传',type:'warning',customClass:'zZindex'});

              return
            }
            if (formData.id){
              uploadSaveModel(this.uploadForm).then((response) => {
                if (response.code == 0) {
                  this.uploadModal=false;
                  this.locationEditUrl(this.uploadForm.id)
                }

              })

            } else{
              uploadSaveModel(formData).then((response) => {
                if (response.code == 0) {

                  // 调用全局挂载的方法
                  this.$store.dispatch('tagsView/delView', this.$route)
                  // 返回上一步路由
                  this.$router.go(-1)
                }

              })
            }



          } else {
            this.$message({"duration":800,message:'表单校验不通过',type:'warning',customClass:'zZindex'});

            return
          }


        })
      },
      handleupLoadSuccess (res, file) {
        file.url = res.data;
        this.uploadForm.id=res.id
        this.uploadList=[];
        this.uploadList.push(file);
        this.uploadForm.photo= file.url
      },

      //后台返回的数据如果和VueTreeselect要求的数据结构不同，需要进行转换
      normalizer(node) {
        //去掉children=[]的children属性
        if(node.children && !node.children.length){
          delete node.children;
        }
        return {
          id: node.title,
          label: node.title,
          children: node.children
        }
      },
      selectTree: function (node, instanceId) {
        this.uploadForm.typeId = node.id
        this.uploadForm.groupName = node.title
      },

      clearOnSelect: function (node, instanceId) {
        if (!node) {
          this.uploadForm.typeId = null
          this.uploadForm.groupName = null
        }
      },
      locationUrl: function (id) {
        if (id) {
          var url = this.baseURL + "diagram/index.html";
          url = url + '?id=' + id + "&t=" + new Date().getTime();
          this.modelerSrc = url
        }
        this.modelerModal = true;

      },
      locationEditUrl: function (id) {
        if (id) {
          var url = this.baseURL + "diagram/index.html";
          url = url + '?id=' + id + "&t=" + new Date().getTime()+"&edit=true";
          this.modelerSrc = url
        }
        this.modelerModal = true;

      },
      cancelModel: function () {
        this.getModelerJsonAction();
      },

      viewImage: function (id) {
        if (id) {
          var url = this.baseURL + "view/def.html?&modelId=" + id
          this.viewImageModelerTmpSrc = url;

        }
        this.viewImageModeler = true;

      },
      exportModel: function (id) {
        if (id) {
          var url = this.baseURL+"/a1bpmn/api/model/export/"+id;
          window.location.href=url
        }

      },
      busModel: function (id) {
        if (id) {
          this.$router.push({name: 'busModel', query: {t: new Date().getTime(),id:id}})
        }
      },
      viewModel: function (id,modelKey) {
        if (id) {
          this.$router.push({name: 'testBpm', query: {t: new Date().getTime(),id:id,modelKey:modelKey}})
        }
      },
      viewVar: function (id) {
        if (id) {
          var exist = []
          getVar(id).then((response) => {
            var data = response.data
            this.code = true;
            var html = '';
            if (data){
              if (data.length>0){
                for (var i in data) {
                  html+='<br/>';
                  if (exist.indexOf(data[i].sequenceFlow.id)==-1) {

                    html+="源节点:"+data[i].flowNode.name;
                    html+='<br/>';
                    html+="连线:"+data[i].sequenceFlow.id;
                    html+='<br/>';
                    html+="原始表达式:"+data[i].sequenceFlow.conditionExpression+"";
                    html+='<br/>';
                    html+="表达式提取变量:";
                    html+='<br/>';
                    for (var j  in  data[i].nodeList) {
                      html+='<br/>';
                      html+=data[i].nodeList[j].name;
                    }
                    exist.push(data[i].sequenceFlow.id)
                  }

                }
              }else{
                html="暂无变量"
              }
            }else{
              html="暂无变量"
            }

            this.varHtml = html;
          })
        }

      },
      versionManager: function (id, modelKey) {

        this.$router.push({name: 'versionManager', query: {t: new Date().getTime(), "modelKey": modelKey}})
      },
      openModelDialog: function () {
        var url = this.baseURL;
        url = url + "diagram/index.html" + "?t=" + new Date().getTime();
        this.modelerSrc = url
        this.modelerModal = true;
      },
      openModelDiffDialog: function () {
        this.modelerSrc = "http://diff.pangubpm.com/"
        this.modelerModal = true;
      },
      openModelUploadDialog: function () {
        this.uploadModal = true;
      },
      publishModel: function (id) {
        publishModel(id).then((response) => {
          if (response.code == 0) {
            this.$message({"duration":800,message:'发布成功',type:'success',customClass:'zZindex'});

            this.getModelerJsonAction();
          } else {
            this.$message({"duration":800,message:response.msg,type:'warning',customClass:'zZindex'});

          }

        })
      },
      queryFormCreateTime: function (e) {
        this.queryForm.createTime = e;
      },
      refreshTask: function (data) {
        if (data){
          if (data[0]){
            if (data[0].parentId == '-1') {
              this.queryForm.groupId = ""
            } else {
              this.queryForm.groupId = data[0].id;

            }
          }

        }

        this.queryForm.procDefName = ""
        this.queryForm.subject = ""
        this.queryForm.page=1
        this.getModelerJsonAction()


      },
      queryMethod: function () {
        getHisInstanceList(this.queryForm).then((response) => {
          this.tableData = response.data
          this.total = parseInt(response.count);

        })
      },
      getModelerJsonAction: function () {
        getHisInstanceList(this.queryForm).then((response) => {
          this.tableData = response.data
          this.total = parseInt(response.count);

        })
      },
      getData: function () {
        getBpmnModelCategory().then((response) => {
          this.categoryData = response.data

        })
        this.getModelerJsonAction();

      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.getModelerJsonAction()
      },
      handleClick(data) {
        this.$router.push({name: 'resurrection_instance_setting', query: {t: new Date().getTime(), 'pid': data.procId}})

      },
      search() {
        this.queryForm.page = 1
        this.queryForm.type = 2
        this.queryForm.typeKey = ""
        this.queryMethod()
        this.queryForm.type = 5
      },
      reset() {
        this.queryForm.procDefName = ""
        this.queryForm.subject = ""
        this.queryMethod();
      }

    }

  }

</script>
<style lang="scss">
  .task-card {
    margin-top: 10px;
  }

  .CodeMirror {
    /* Set height, width, borders, and global font properties here */
    font-family: monospace;
    height: auto;
    color: black;
    direction: ltr;
  }

  .CodeMirror-scroll {
    height: auto;
    overflow-y: hidden;
    overflow-x: auto;
  }
</style>
